#!@TERMUX_PREFIX@/bin/sh
set -e -u

SCRIPTNAME=termux-download
show_usage () {
    echo "Usage: $SCRIPTNAME [-d description] [-t title] url-to-download"
    echo "Download a resource using the system download manager."
    echo "  -d description  description for the download request notification"
    echo "  -t title        title for the download request notification"
    echo "  -p path         full path to which the file should be downloaded"
    exit 0
}

ARG_D=""
OPT_D=""
ARG_T=""
OPT_T=""
ARG_P=""
OPT_P=""

while getopts :hd:t:p: option
do
    case "$option" in
	h) show_usage;;
	d) ARG_D="--es description"; OPT_D="$OPTARG";;
	t) ARG_T="--es title"; OPT_T="$OPTARG";;
	p) ARG_P="--es path"; OPT_P="$OPTARG";;
	?) echo "$SCRIPTNAME: illegal option -$OPTARG"; exit 1;
    esac
done
shift $((OPTIND-1))

if [ $# -lt 1 ]; then echo "$SCRIPTNAME: no url specified"; exit 1; fi
if [ $# -gt 1 ]; then echo "$SCRIPTNAME: too many arguments"; exit 1; fi

URL_TO_DOWNLOAD="$1"

set --
if [ -n "$ARG_D" ]; then set -- "$@" $ARG_D "$OPT_D"; fi
if [ -n "$ARG_T" ]; then set -- "$@" $ARG_T "$OPT_T"; fi
if [ -n "$ARG_P" ]; then set -- "$@" $ARG_P "$OPT_P"; fi
set -- "$@" "$URL_TO_DOWNLOAD"

@TERMUX_PREFIX@/libexec/termux-api Download "$@"
